﻿<%@ WebHandler Language="C#" Class="SIPO.Web.AjaxHandler.Administration.Catalog.recImpositionhandler" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;

using SIPO.Library.DataAccess.Transaction;
using SIPO.Library.DomainObject.Transaction;
using SIPO.Library.DataAccess.Administration;
using SIPO.Library.DomainObject.Administration;
using SIPO.Library.DataAccess.Administration.Catalog;
using SIPO.Library.DomainObject.Administration.Catalog;
using SIPO.Library.Enum;
using SIPO.Web.Support;

using Newtonsoft.Json.Linq;

namespace SIPO.Web.AjaxHandler.Administration.Catalog
{

    public class recImpositionhandler : SIPO.Web.BaseHandler
    {

        private recImpositionRepo recImpositionDal = new recImpositionRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        private recImpositionDetailRepo recImpositionDetailDal = new recImpositionDetailRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        private recLogRepo logDal = new recLogRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        private string MethodName = string.Empty;

        public override void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);

            MethodName = context.Request.Params["method"];

            switch (MethodName.ToLower())
            {
                case ("insert"):
                    context.Response.Write(Insert(context));
                    break;
                case ("insertnodialog"):
                    context.Response.Write(InsertNoDialog(context));
                    break;
                case ("update"):
                    System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream);
                    string jsonString = string.Empty;
                    jsonString = context.Server.UrlDecode(sr.ReadToEnd());
                    JObject jObj = string.IsNullOrEmpty(jsonString) ? null : JObject.Parse(jsonString);
                    sr.Close();
                    sr.Dispose();
                    context.Response.Write(Update(context, jObj));
                    break;
                case ("delete"):
                    sr = new System.IO.StreamReader(context.Request.InputStream);
                    jsonString = string.Empty;
                    jsonString = context.Server.UrlDecode(sr.ReadToEnd());
                    jObj = string.IsNullOrEmpty(jsonString) ? null : JObject.Parse(jsonString);
                    sr.Close();
                    sr.Dispose();
                    context.Response.Write(Delete(context, jObj));
                    break;
                case ("getdata"):
                    context.Response.Write(GetData(context));
                    break;
                case ("getdatabyimpositionid"):
                    context.Response.Write(GetDataByImpositionID(context));
                    break;

                default:
                    // do nothing
                    break;
            }

        }

        public override bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private string InsertNoDialog(HttpContext context)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                recTransactionTypeRepo transTypeDal = new recTransactionTypeRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
                //recTransactionType transType = transTypeDal.GetByLikeTransTypeName("iuran berkala");
                recTransactionType transType = transTypeDal.GetByTransTypeCode(2);
                recImposition obj = new recImposition();
                obj.YearReport = short.Parse(context.Request.Params["TahunLapKeu"].ToString());
                obj.DebtorSectorID = int.Parse(context.Request.Params["DebtorSectorID"].ToString());
                if (context.Request.Params["DebtorValue"].ToString() != "")
                    obj.DebtorValue = Helper.ToDecimal(context.Request.Params["DebtorValue"].ToString(), System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian); // because from UI form is id-ID formatted.                
                if (context.Request.Params["OJKValue"].ToString() != "")
                    obj.OJKValue = Helper.ToDecimal(context.Request.Params["OJKValue"].ToString(), System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian); // because from UI form is id-ID formatted.                                
                if (context.Request.Params["ImpositionBaseID"].ToString() != "")
                    obj.ImpositionBaseID = int.Parse(context.Request.Params["ImpositionBaseID"]);
                obj.Maximal = Helper.ToDecimal(context.Request.Params["Maximal"].ToString(), System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian); // because from UI form is id-ID formatted.                                
                obj.Minimal = Helper.ToDecimal(context.Request.Params["Minimal"].ToString(), System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian); // because from UI form is id-ID formatted.                                
                obj.DebtorID = int.Parse(context.Request.Params["DebtorID"]);
                obj.SubSubSectorID = int.Parse(context.Request.Params["SubSubSectorID"]);
                obj.TariffValue = decimal.Parse(context.Request.Params["TarifValue"]);
                obj.TariffID = int.Parse(context.Request.Params["TarifID"]);
                obj.Percentage = decimal.Parse(context.Request.Params["Percentage"]);
                obj.IsFormula = bool.Parse(context.Request.Params["IsFormula"]);
                obj.TransTypeID = transType.TransTypeID;
                obj.CreatedDate = DateTime.Now;
                obj.CreatedBy = base.UserLoggedIn;
                if (context.Request.Files.Count > 0)
                {
                    HttpPostedFile hpf = context.Request.Files[0] as HttpPostedFile;
                    string FileName = string.Empty;
                    if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
                    {
                        string[] files = hpf.FileName.Split(new char[] { '\\' });
                        FileName = files[files.Length - 1];
                    }
                    else
                    {
                        FileName = hpf.FileName;
                    }

                    byte[] datas = new byte[hpf.ContentLength];
                    hpf.InputStream.Position = 0;
                    hpf.InputStream.Read(datas, 0, hpf.ContentLength);

                    obj.Attachment = datas;
                    obj.AttachedFileName = FileName;

                    hpf.InputStream.Close();
                    hpf.InputStream.Dispose();
                }
                else
                {
                    recImposition imposition = recImpositionDal.GetById(int.Parse(context.Request.Params["ImpositionID"]));
                    if (imposition != null)
                    {
                        if (imposition.AttachedFileName != "")
                            obj.AttachedFileName = imposition.AttachedFileName;
                        if (imposition.Attachment != null)
                            obj.Attachment = imposition.Attachment;
                    }
                }

                recImpositionDetail objDetail = new recImpositionDetail();
                if (context.Request.Params["DebtorValue"].ToString() != "")
                    objDetail.DebtorValue = Helper.ToDecimal(context.Request.Params["DebtorValue"].ToString(), System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian); // because from UI form is id-ID formatted.                
                if (context.Request.Params["OJKValue"].ToString() != "")
                    objDetail.OJKValue = Helper.ToDecimal(context.Request.Params["OJKValue"].ToString(), System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian); // because from UI form is id-ID formatted.                                
                if (base.UserTypeID == 2)
                    objDetail.OJKValue = 0;
                else if (base.UserTypeID == 3)
                    objDetail.DebtorValue = 0;
                objDetail.IsActive = true;
                objDetail.TransDate = DateTime.Now;
                objDetail.CreateDate = DateTime.Now;
                objDetail.CreateBy = base.UserLoggedIn;

                recImposition recImposition = recImpositionDal.GetById(int.Parse(context.Request.Params["ImpositionID"]), obj.YearReport.ToString(), obj.DebtorSectorID, (int)obj.SubSubSectorID);
                if (recImposition != null)
                {
                    obj.ImpositionID = recImposition.ImpositionID;
                    obj.UpdatedBy = base.UserLoggedIn;
                    obj.UpdatedDate = DateTime.Now;

                    objDetail.ImpositionDetailID = recImposition.recImpositionDetail.ImpositionDetailID;
                    objDetail.UpdateBy = base.UserLoggedIn;
                    objDetail.UpdateDate = DateTime.Now;
                    if (recImposition.recImpositionDetail.CalculationID != 0)
                    {
                        //koreksi
                        objDetail.CalculationID = recImposition.recImpositionDetail.CalculationID;
                        recImpositionDal.SaveCorrection(obj, objDetail);// update imposition, update impositiondetail isactive = 0 ,save impositiondetail, run [dbo].[SP_GenPeriodicDues]
                    }
                    else
                    {
                        //edit
                        recImpositionDal.UpdateCorrection(obj, objDetail);//update imposition, impositiondetail, run [dbo].[SP_GenPeriodicDues]
                    }
                }
                else
                    recImpositionDal.Save(obj, objDetail);// save imposition,impositiondetail, run [dbo].[SP_GenPeriodicDues]

                helper.Message = "Data berhasil di simpan !";
                helper.IsSuccess = true;
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Insert";
                log.LogMessage = helper.Message;
                log.LogSource = "recImpositionhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);

            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }
        private string Insert(HttpContext context)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                var data = context.Request.Form;

                var debtorId = data["ddlDebtor"];
                var debtorSectorId = data["hfDebtorSectorId"];
                var tahunLapKeu = data["ddlTahunLapKeu"];
                var subSubSectorId = data["ddlSubSubSector"];
                var impositionbaseid = data["ddlImpositionBase"];
                var percentage = data["txtPercentage"];
                var minValue = data["txtTarifMin"];
                var maxValue = data["txtTarifMax"];
                var debiturValue = data["txtDebtorValue"];
                var ojkValue = data["txtOJKValue"];
                var tariffId = data["hfTarifId"];
                var tariffValue = data["hfTarifValue"];

                recTransactionTypeRepo transTypeDal = new recTransactionTypeRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
                //recTransactionType transType = transTypeDal.GetByLikeTransTypeName("iuran berkala");
                recTransactionType transType = transTypeDal.GetByTransTypeCode(2);
                recImposition obj = new recImposition();
                obj.YearReport = short.Parse(tahunLapKeu);
                obj.DebtorSectorID = int.Parse(debtorSectorId);
                if (!string.IsNullOrEmpty(debiturValue))
                {
                    if (debiturValue.ToString().IndexOf(',') > 0)
                        obj.DebtorValue = Helper.ToDecimal(debiturValue, System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian); // because from UI form is id-ID formatted.
                    else
                        obj.DebtorValue = Helper.ToDecimal(debiturValue, System.Globalization.NumberStyles.Number, Helper.Culture.English); // because from UI form is id-ID formatted.
                }
                if (!string.IsNullOrEmpty(ojkValue))
                {
                    if (ojkValue.ToString().IndexOf(',') > 0)
                        obj.OJKValue = Helper.ToDecimal(ojkValue, System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian); // because from UI form is id-ID formatted.                
                    else
                        obj.OJKValue = Helper.ToDecimal(ojkValue, System.Globalization.NumberStyles.Number, Helper.Culture.English); // because from UI form is id-ID formatted.                
                }
                obj.ImpositionBaseID = int.Parse(impositionbaseid);
                obj.Maximal = Helper.ToDecimal(maxValue, System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian); // because from UI form is id-ID formatted.
                obj.Minimal = Helper.ToDecimal(minValue, System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian); // because from UI form is id-ID formatted.
                obj.DebtorID = int.Parse(debtorId);
                obj.TariffValue = Helper.ToDecimal(tariffValue, System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian); // because from UI form is id-ID formatted.
                obj.TariffID = int.Parse(tariffId);
                obj.Percentage = Helper.ToDecimal(percentage, System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian); // because from UI form is id-ID formatted.
                obj.TransTypeID = transType.TransTypeID;
                obj.CreatedDate = DateTime.Now;
                obj.CreatedBy = base.UserLoggedIn;
                if (context.Request.Files.Count > 0)
                {
                    HttpPostedFile hpf = context.Request.Files[0] as HttpPostedFile;
                    string FileName = string.Empty;
                    if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
                    {
                        string[] files = hpf.FileName.Split(new char[] { '\\' });
                        FileName = files[files.Length - 1];
                    }
                    else
                    {
                        FileName = hpf.FileName;
                    }

                    byte[] datas = new byte[hpf.ContentLength];
                    hpf.InputStream.Position = 0;
                    hpf.InputStream.Read(datas, 0, hpf.ContentLength);

                    obj.Attachment = datas;
                    obj.AttachedFileName = FileName;

                    hpf.InputStream.Close();
                    hpf.InputStream.Dispose();
                }

                recImpositionDetail objDetail = new recImpositionDetail();
                if (!string.IsNullOrEmpty(debiturValue))
                {
                    if (debiturValue.ToString().IndexOf(',') > 0)
                        objDetail.DebtorValue = Helper.ToDecimal(debiturValue, System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian); // because from UI form is id-ID formatted.
                    else
                        objDetail.DebtorValue = Helper.ToDecimal(debiturValue, System.Globalization.NumberStyles.Number, Helper.Culture.English); // because from UI form is id-ID formatted.
                }
                if (!string.IsNullOrEmpty(ojkValue))
                {
                    if (ojkValue.ToString().IndexOf(',') > 0)
                        objDetail.OJKValue = Helper.ToDecimal(ojkValue, System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian); // because from UI form is id-ID formatted.
                    else
                        objDetail.OJKValue = Helper.ToDecimal(ojkValue, System.Globalization.NumberStyles.Number, Helper.Culture.English); // because from UI form is id-ID formatted.
                }
                objDetail.IsActive = true;
                objDetail.TransDate = DateTime.Now;
                objDetail.CreateDate = DateTime.Now;
                objDetail.CreateBy = base.UserLoggedIn;

                recImpositionDal.Save(obj, objDetail);//save to imposition,impositiondetail

                helper.Message = "Data berhasil di simpan !";
                helper.IsSuccess = true;
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Insert";
                log.LogMessage = helper.Message;
                log.LogSource = "recImpositionhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);

            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }



        private string Update(HttpContext context, JObject jo)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                recImposition obj = new recImposition();
                obj.ImpositionID = (int)jo["ImpositionID"];
                obj.YearReport = (Int16)jo["Year"];
                obj.DebtorSectorID = (int)jo["DebtorSectorID"];
                obj.DebtorValue = (decimal)jo["DebtorValue"];
                obj.OJKValue = (decimal)jo["OJKValue"];
                obj.ImpositionBaseID = (int)jo["ImpositionBaseID"];
                obj.AttachedFileName = (string)jo["AttachedFileName"];
                obj.DirectoryLocation = (string)jo["DirectoryLocation"];
                //obj.IsReviewed = (bool)jo["IsReviewed"];
                //obj.ReviewedDate = DateTime.ParseExact(jo["ReviewedDate"].ToString(), "dd/MM/yyyy", new System.Globalization.CultureInfo("id-ID"));
                //obj.ReviewedBy = (string)jo["ReviewedBy"];
                //obj.IsCalculate = false;
                //obj.IsCorporateAction = false;

                obj.UpdatedDate = DateTime.Now;
                obj.UpdatedBy = base.UserLoggedIn;

                recImpositionDal.Update(obj);

                helper.Message = "Data berhasil di ubah !";
                helper.IsSuccess = true;
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Update";
                log.LogMessage = helper.Message;
                log.LogSource = "recImpositionhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        private string Delete(HttpContext context, JObject jo)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                var strId = (string)jo["ImpositionID"];

                string[] ids = strId.Split(',');
                foreach (string id in ids)
                {
                    int intID = Convert.ToInt32(id);
                    recImpositionDal.Delete(intID);
                }

                helper.IsSuccess = true;
                helper.Message = "Data berhasil di hapus !";
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Delete";
                log.LogMessage = helper.Message;
                log.LogSource = "recImpositionhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);

            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        private string GetData(HttpContext context)
        {
            //var subsubSectorIds = "";
            //var debtorId = "";
            //subsubSectorIds = " WHERE " + "recSubSubSector.SubSubSectorID IN (" + base.SubSubSectorIDs + ")";
            //debtorId = "AND recDebtor.DebtorID = " + base.DebtorID;
            //string parameters = Helper.JqGridFilterToSQLParams(context);
            //if (parameters == "")
            //{
            //    if (base.DebtorID != null)
            //        parameters = parameters + subsubSectorIds + debtorId;
            //    else
            //        parameters = parameters + subsubSectorIds;
            //}
            //else
            //{
            //    subsubSectorIds = " AND " + "recSubSubSector.SubSubSectorID IN (" + base.SubSubSectorIDs + ")";
            //    if (base.DebtorID != null)
            //        parameters = parameters + subsubSectorIds + debtorId;
            //    else
            //        parameters = parameters + subsubSectorIds;
            //}
            string parameters = Helper.JqGridFilterToSQLParams(context);

            if (!string.IsNullOrEmpty(parameters)) // If Current User while using filter on Grid
            {
                if (base.DebtorID.HasValue) // User Is Debitur
                {
                    parameters += " AND recDebtor.DebtorID = " + base.DebtorID;
                    if (!string.IsNullOrEmpty(base.SubSubSectorIDs))
                    {
                        parameters += " AND recSubSubSector.SubSubSectorID IN (" + base.SubSubSectorIDs + ")";
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(base.SubSubSectorIDs))
                    {
                        parameters += " AND recSubSubSector.SubSubSectorID IN (" + base.SubSubSectorIDs + ")";
                    }
                }
            }
            else
            {
                if (base.DebtorID.HasValue) // User Is Debitur
                {
                    parameters = " WHERE recDebtor.DebtorID = " + base.DebtorID;
                    if (!string.IsNullOrEmpty(base.SubSubSectorIDs))
                    {
                        parameters += " AND recSubSubSector.SubSubSectorID IN (" + base.SubSubSectorIDs + ")";
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(base.SubSubSectorIDs))
                    {
                        parameters = " WHERE recSubSubSector.SubSubSectorID IN (" + base.SubSubSectorIDs + ")";
                    }
                }
            }
            parameters += " AND transactions.recImpositionDetail.IsActive = 1";

            int page = 1;
            int.TryParse(context.Request.QueryString["page"] ?? "1", out page);

            int pageSize = 10;
            int.TryParse(context.Request.QueryString["rows"] ?? "10", out pageSize);

            string sidx = ((context.Request.QueryString["sidx"]) == null ? recImposition.Fields.DebtorSectorID : context.Request.QueryString["sidx"].ToString());

            string sord = ((context.Request.QueryString["sord"]) == null ? "ASC" : context.Request.QueryString["sord"].ToString());

            int totalCount = 0;
            int totalPages = 0;
            List<recImposition> pagedList = null;

            try
            {
                totalCount = Convert.ToInt32(recImpositionDal.SelectScalar(SQL.Function.Aggregate.Count, "recImposition.ImpositionID", parameters));

                decimal dc = decimal.Ceiling(Convert.ToDecimal(totalCount) / Convert.ToDecimal(pageSize));
                totalPages = Convert.ToInt32(dc);

                pagedList = recImpositionDal.GetList(pageSize, page, sidx, sord, parameters);
            }
            catch (Exception ex)
            {
                recLog log = new recLog();
                log.LogEvent = "GetData";
                log.LogMessage = ex.Message;
                log.LogSource = "recImpositionhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
                log.Dispose();
            }
            finally
            {

            }

            // send params into jqGrid's format
            var gridData = new
            {
                page = page,
                total = totalPages,
                records = totalCount,
                rows = pagedList,
            };

            return Newtonsoft.Json.JsonConvert.SerializeObject(gridData);

        }

        private string GetDataByImpositionID(HttpContext context)
        {
            int impositionId = int.Parse(context.Request.Params["ImpositionId"].ToString());
            string parameters = Helper.JqGridFilterToSQLParams(context);
            if (!string.IsNullOrEmpty(parameters))
                parameters += " AND transactions.recImposition.ImpositionID = " + impositionId;
            else
                parameters = " WHERE transactions.recImposition.ImpositionID = " + impositionId;

            int page = 1;
            int.TryParse(context.Request.QueryString["page"] ?? "1", out page);

            int pageSize = 10;
            int.TryParse(context.Request.QueryString["rows"] ?? "10", out pageSize);

            string sidx = ((context.Request.QueryString["sidx"]) == null ? recImposition.Fields.DebtorSectorID : context.Request.QueryString["sidx"].ToString());

            string sord = ((context.Request.QueryString["sord"]) == null ? "ASC" : context.Request.QueryString["sord"].ToString());

            int totalCount = 0;
            int totalPages = 0;
            List<recImposition> pagedList = null;

            try
            {
                totalCount = Convert.ToInt32(recImpositionDetailDal.SelectScalar(SQL.Function.Aggregate.Count, "recImpositionDetail.ImpositionDetailID", parameters));

                decimal dc = decimal.Ceiling(Convert.ToDecimal(totalCount) / Convert.ToDecimal(pageSize));
                totalPages = Convert.ToInt32(dc);

                pagedList = recImpositionDal.GetListForCorrectionHistory(pageSize, page, sidx, sord, parameters);
            }
            catch (Exception ex)
            {
                recLog log = new recLog();
                log.LogEvent = "GetDataByImpositionID";
                log.LogMessage = ex.Message;
                log.LogSource = "recImpositionhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
                log.Dispose();
            }
            finally
            {

            }

            // send params into jqGrid's format
            var gridData = new
            {
                page = page,
                total = totalPages,
                records = totalCount,
                rows = pagedList,
            };

            return Newtonsoft.Json.JsonConvert.SerializeObject(gridData);

        }

    }

}